/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved. distributed with this file and
 * available online at
 */
package com.lap.auth.application.msg;

import org.springframework.stereotype.Service;
import com.lap.auth.application.msg.assembler.MsgTemplateAssembler;
import com.lap.auth.application.msg.command.CreateMsgTemplateCmd;
import com.lap.auth.application.msg.command.UpdateMsgTemplateCmd;
import com.lap.auth.application.msg.dto.MsgTemplateDto;
import com.lap.auth.application.msg.dto.QueryMsgTemplatePageQuery;
import com.lap.auth.application.msg.repository.MsgTemplateQueryRepository;
import com.lap.auth.domain.msg.MsgTemplate;
import com.lap.auth.domain.msg.repository.MsgTemplateRepository;
import com.lap.auth.domain.msg.service.MsgTemplateValidator;
import com.lap.framework.dto.page.PageResponse;
import lombok.RequiredArgsConstructor;

/**
 * 消息模版应用服务层
 *
 * <ol>
 * <li>不谈业务规则，只谈基础规则（加密/解密是技术实现，业务不关注）
 * <li>取数，赋值，对象转换到在这层执行
 * <li>命名有规范，动词+领域名字
 * <li>如查询比较多，建议分开领域QueryAppService,如:分页查询，分页查询返回关联字段
 * </ol>
 */
@RequiredArgsConstructor
@Service
public class MsgTemplateAppService {

  private final MsgTemplateAssembler msgTemplateAssembler;
  private final MsgTemplateValidator msgTemplateValidator;
  private final MsgTemplateRepository msgTemplateRepository;
  private final MsgTemplateQueryRepository msgTemplateQueryRepository;

  public PageResponse<MsgTemplateDto> queryMsgTemplatesByPage(QueryMsgTemplatePageQuery query) {
    return msgTemplateQueryRepository.findByConditionPaged(query);
  }

  public Integer createMsgTemplate(CreateMsgTemplateCmd cmd) {
    MsgTemplate msgTemplate = msgTemplateAssembler.toDomain(cmd);
    msgTemplateValidator.validateCodeUnique(msgTemplate, false);
    return msgTemplateRepository.save(msgTemplate);
  }

  public int updateMsgTemplate(Integer id, UpdateMsgTemplateCmd cmd) {
    msgTemplateValidator.assertMsgTemplateExists(id);
    MsgTemplate msgTemplate = msgTemplateAssembler.toDomain(id, cmd);
    msgTemplateValidator.validateCodeUnique(msgTemplate, true);
    return msgTemplateRepository.save(msgTemplate);
  }

  public Integer deleteMsgTemplate(Integer id) {
    msgTemplateValidator.assertMsgTemplateExists(id);
    return msgTemplateRepository.deleteById(id);
  }
}
